<?php
/**
 * Created by PhpStorm.
 *
 * @Date: 2018-01-15
 * @Time: 15:25
 * @Author: cdkay
 * @Email: network@iyuanma.net
 *
 * @File： SpecialArticleMessage.php
 */
namespace app\api\model\special;

use app\api\model\user\Users;
use think\Db;
use think\Log;
use think\Model;

class SpecialArticleMessage extends Model {
    protected $table = 'special_article_message';
    protected $pk = 'message_id';

    /**
     * getMessage
     * 获取专栏文章留言数据
     *
     * @param int $aid 文章id
     * @param int $page 当前页数
     * @param int $limit 每页查询数据条数
     * @return array
     */
    public function getMessage($aid, $page=1, $limit=10)
    {
        $data = $this::all(function($query) use (&$aid, &$page, &$limit) {
            $query->field('message_id, message_content, message_time, u.id as user_id,u.mobile as user_mobile, u.nickname as user_nickname, u.avatar as user_avatar')
                ->join('users u', 'message_user=u.id', 'left')
                ->where('message_article', $aid)
                ->order('message_time desc')
                ->page($page, $limit);
        });

        if (empty($data)) return [];

        $result = [];
        foreach ($data as $key=>$val) {
            $val->user_nickname = ($val->user_nickname?:mobile_hidden(substr($val->user_mobile, 0, 11)))?:$val->user_id;
            unset($val->user_mobile);
            $val->user_avatar = $val->user_avatar??Users::defaultAvatar();

            $val->message_time = tranTime($val->message_time);

            unset($val->user_id);
            $result[] = $val->getData();
        }

        return $result;
    }

    /**
     * saveMessage
     * 保存留言数据
     *
     * @author zhengkai
     * @date 2018-01-16
     *
     * @param array $param
     * @return bool
     */
    public function saveMessage($param=[])
    {
        // 传入参数检测
        $param_list = ['message_article', 'message_user', 'message_content'];
        foreach ($param as $key=>$val){
            if (!in_array($key, $param_list)) {
                Log::error('保存留言到数据库错误信息：参数不正确');
                return false;
            }
        }

        Db::startTrans();
        try {
            $this::create([
                'message_article' => $param['message_article'],
                'message_user' => $param['message_user'],
                'message_content' => $param['message_content'],
                'message_time' => time()
            ]);

            Db::commit();

            return true;
        } catch (\Exception $e) {
            Log::error('保存留言到数据库错误信息：'.$e->getMessage());

            Db::rollback();

            return false;
        }
    }
}